#pragma once
#include <iostream>
#include <unistd.h>
#include <sys/wait.h>
#include <fcntl.h>

#include "../comm/util.hpp"
#include "../comm/log.hpp"

using namespace ns_util;
using namespace ns_log;

namespace ns_compiler
{
    class compiler
    {
    public:
        compiler()
        {
        }

        static bool compile(const std::string &file_name)
        {
            int pid = fork();
            if (pid < 0)
            {
                LOG(Error) << "编译程序创建失败" << "\n";
                return false;
            }
            else if (pid == 0)
            {
                umask(0);
                int _stderr = open(PathUtil::CompileErr(file_name).c_str(), O_CREAT | O_WRONLY, 0644);
                if (_stderr < 0)
                {
                    LOG(Error) << "生成CompileErr文件失败" << "\n";
                    exit(1);
                }
                dup2(_stderr, 2);

                execlp("g++", "g++", "-o", PathUtil::Exe(file_name).c_str(), PathUtil::Src(file_name).c_str(), "-D","CompileOnline","-std=c++11", nullptr);
                LOG(Error) << "编译程序启动失败" << "\n";
                exit(2);
            }
            else
            {
                waitpid(pid, nullptr, 0);
                if (FileUtil::IsFileExists(PathUtil::Exe(file_name)))
                {
                    LOG(Info) << PathUtil::Src(file_name) << " 编译成功" << "\n";
                    return true;
                }
            }
            LOG(Error) << "生成可执行程序失败" << "\n";
            return false;
        }

        ~compiler()
        {
        }
    };
}